<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-09-29
 * Time: 13:48
 */

namespace backend\controllers;


use app\models\CtiFile;
use common\helps\Tools;
use common\helps\UploadFiles;

class CtiManagerIvrController  extends CtiManagerController
{

    /**
     * 导入ivr文件的内容
     */
    public $myfile = "";
    public function actionUpload()
    {
        try{
            $model = new CtiFile();
            $file = $_FILES['file'];
            $type = isset($_POST['type'])?$_POST['type']:"cti_ivr";//设置上传的文件类型，如果不设置就是ivr文件
            if (!empty($file)) {
                $count = CtiFile::find()->select("*")->where(["name"=>$file['name']])->count();
                $model->name = $file['name'];
                if ($count>0){//表面所上传的文件已经上传过了，
                    return "1";
                }
                $this->myfile = UploadFiles::common_upload_single($file);
                if(!empty($model->name) && $this->myfile){
                    //开启事务
                    $connection = \Yii::$app->getDb();
                    $transaction = $connection->beginTransaction();
                    $model->type = $type;
                    $model->path = $this->https_url.$this->myfile['filename'];
                    $model->filesize = $file['size'];
                    $model->create_at = time();
                    $model->save();
                    //更新导入了几条记录
                    $model->updateAttributes(['number'=>1]);
                    $transaction->commit();
                    //事务完成，一次性提交
                }
                return "true";
            }else{
                return "false";
            }
        }catch (\Exception $e){
            Tools::l($e);
        }
    }

    /**
     * 导入语音文件到freeswitch
     */
    public function actionUploadFs()
    {
        try{
            $res = $this->actionUpload();
            if($res=="true"){//上传到本地成功
                // 现在上传到freeswitch
                $dest = str_replace("/","\\",$this->path.$this->fs_wav_path.'ivr\\8000\\'.$_FILES['file']['name']);
                $ress = copy("./".$this->myfile['filename'],$dest);
                if ($ress){
                    $path['path'] = 'ivr/'.$_FILES['file']['name'];
                    $path['src'] = $this->https_url.$this->myfile['filename'];
                    return json_encode($path);
                }else{
                    return false;
                }
            }else{
                return $res;
            }
        }catch (\Exception $e){
            Tools::l($e);
        }
    }

    /**
     * 保存数据
     */
    public function actionSave(){
        $xml = Tools::arrtoxml($_POST['data']);//将数组转化为xml数据
        //将conf/auto_configs/callcenter.conf.xml配置文件里面的内容替换掉，打开ivr
        $file = $this->path.'conf\\dialplan\\default.xml';
        if ($xml->menu['show-ivr']=="hidden"){//如果开关关闭了就表明关闭ivr
            $search = ['extension name="IMSGatewayInbound"','action','application="ivr"','data="my_in_ivr"'];
            $replace = ['extension name="IMSGatewayInbound"','action','application="ivr"','data=""'];
        }else{//开启ivr
            $search = ['extension name="IMSGatewayInbound"','action','application="ivr"','data=""'];
            $replace = ['extension name="IMSGatewayInbound"','action','application="ivr"','data="my_in_ivr"'];
        }
        $res = $this->replaceXmlFileConfig($file,$search,$replace,true);
        if ($res){
            $res2 = file_put_contents($file,$res);//替换掉服务器里面的文件内容
            if(!$res2){
                return false;
            }
        }
        $xmlContents = $xml->asXML();
        $xmlContents = str_replace(">",">\n",$xmlContents);//让文件实现换行，好读懂
        $res1 = file_put_contents($this->path.'conf\\ivr_menus\\my_in_ivr.xml',$xmlContents);//替换掉freeswitch里面的文件内容
        $https_url = $this->https_url;
        $temp = strpos($_POST['path'],$https_url);
        $res2 = file_put_contents(substr($_POST['path'],strlen($https_url)+$temp,strlen($_POST['path'])-strlen($https_url)),$xmlContents);//替换掉服务器里面的文件内容
        if ($res1>0&&$res2>0){
            $this->execFSBgapi("reloadxml");
            return true;
        }else{
            return false;
        }
    }

    /**
     * 解析xml文件,内容解析成数组数据
     */
    public function actionParseIvrXmlFile($id){
        $file = CtiFile::findOne($id);
        $params = $file->params;
        $file = $file->path;
        if (strpos($file,$this->https_url)!==false){//文件名字包含了https://10.105.203.200/crms/backend/web/
            $file = substr($file,strlen($this->https_url),strlen($file));
        }
        $file_contents_xml_ = json_decode(json_encode(simplexml_load_file("./".$file)),true);//将xml字符串转化为xml对象
        $menu = $file_contents_xml_['menu'];
        if (!isset($menu[0])){
            $file_contents_xml['menu'] = [$menu];
        }else{
            $file_contents_xml = $file_contents_xml_;
        }
        foreach ( $menu as $k=>$v){
            if (isset($v['entry'])){
                if(count($v['entry'])<1){//表示有属性就说明数组只有一个
                    $entry["@attributes"]= ["action"=>"","digits"=>"","param"=>""];
                    $attr = $entry;
                    $file_contents_xml['menu'][$k]['entry'] = [$attr];
                }elseif (count($v['entry'])==1){
                    $attr = $v['entry'];
                    $file_contents_xml['menu'][$k]['entry'] = [$attr];
                }
            }
        }
        $res['data'] = $file_contents_xml;
        $res['switchXml'] = $params;
        return json_encode($res);
    }

    /**
     * 文件列表
     */
    public function actionFileList()
    {
        return $this->getFileList(new CtiFile(),"cti_ivr");
    }





}